package server.handle;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import server.CenterServer;
import server.support.IServerInfoMap;
import server.support.ServerInfoMap;
import support.RpcInfo;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Handler;

//主要用于接受服务注册
public class ServerInboundHandle extends SimpleChannelInboundHandler<RpcInfo> {
    public static IServerInfoMap serverInfoMap = new ServerInfoMap();
    static Logger logger = LoggerFactory.getLogger(ServerInboundHandle.class);
    public static String REGIST_OK = null;
    public static String REGIST_FAIL ="500";
    Map<Integer, IDispatchHandle> handleMap;

    public ServerInboundHandle() {
        this.handleMap= new HashMap<>();
        handleMap.put(0,new RegisteHandle());
        handleMap.put(1,new PostHandle());
        logger.info("IDispatchHandle注册完成...");
    }

    protected void channelRead0(ChannelHandlerContext ctx, RpcInfo msg) throws Exception {
        NioSocketChannel channel = (NioSocketChannel) ctx.pipeline().channel();

        int command = msg.getCommand();
        logger.info("新的请求到来,msg = {}",msg);
        IDispatchHandle iDispatchHandle = handleMap.get(command);

        if(iDispatchHandle==null){
            logger.error("无效请求,找不到对应的处理器...:command:{}",command);
        }

        iDispatchHandle.dispatch(msg,channel);
    }

    @Override
    public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
        super.channelUnregistered(ctx);
        NioSocketChannel channel = (NioSocketChannel) ctx.channel();
        serverInfoMap.unregiste(channel.remoteAddress().getAddress().getHostAddress(),channel.remoteAddress().getPort());
    }
}
